<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height: 60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="doAdd"
              >新增角色</el-button>
            </el-row>
            <!-- 表格 -->
            <el-table :data="roles">
              <el-table-column
                label="序号"
                width="120"
                type="index"
                :index="indexFn"
              />
              <el-table-column label="角色名称" width="240" prop="name" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button
                    size="small"
                    type="success"
                    @click="hAssign(scope.row.id)"
                  >分配权限</el-button>
                  <el-button
                    size="small"
                    type="primary"
                    @click="doEait(scope.row)"
                  >编辑</el-button>
                  <el-button
                    size="small"
                    type="danger"
                    @click="deleteRole(scope.row.id)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-row
              type="flex"
              justify="center"
              align="middle"
              style="height: 60px"
            >
              <!-- 分页组件 -->
              <el-pagination
                :current-page="pageParams.page"
                :page-sizes="[1, 2, 3, 4]"
                :page-size="pageParams.pagesize"
                layout="total, sizes, prev, pager, next"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
    <!-- 新增弹框 -->
    <el-dialog
      :title="flag ? '编辑' : '添加'"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="showDialog"
      @close="reset"
    >
      <el-form
        ref="roleForm"
        :model="roleForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="roleForm.description" />
        </el-form-item>
      </el-form>
      <!-- 底部 -->
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button size="small" @click="showDialog = false">取消</el-button>
          <el-button
            size="small"
            type="primary"
            @click="hSubmit"
          >确定</el-button>
        </el-col>
      </el-row>
    </el-dialog>
    <el-dialog
      title="分配权限"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="showDialogAssign"
    >
      <assign-permission
        v-if="showDialogAssign"
        :cur-id="curId"
        @success="Hsuccess"
      />
    </el-dialog>
  </div>
</template>

<script>
import { getRoles, deleteRole, addRole, updateRole } from '@/api/setting'
import assignPermission from './assignPermission.vue'
export default {
  components: { assignPermission },
  data() {
    return {
      showDialogAssign: false, // 控制分配权限弹框
      roles: [],
      total: 0,
      pageParams: {
        page: 1, // 查询第一页
        pagesize: 2 // 每页两条  --- 要与pagination中page-size一致
      },
      showDialog: false,
      roleForm: {
        name: '',
        description: ''
      },
      // 校验规则
      rules: {
        name: [{ required: true, message: '角色名必填！', targgle: 'blur' }],
        description: [
          { required: true, message: '角色描述必填！', targgle: 'blur' }
        ]
      },
      // 区分添加和编辑
      flag: false,
      // 用于子组件获取当前用户的权限信息
      curId: ''
    }
  },
  created() {
    this.loadRoles(this.pageParams)
  },
  methods: {
    // 子组件关闭弹框，父组件赋值
    Hsuccess() {
      this.showDialogAssign = false
    },
    // 弹出分配权限弹框
    hAssign(id) {
      this.showDialogAssign = true
      this.curId = id
    },
    // 重置功能
    reset() {
      this.$refs.roleForm.resetFields()
    },
    async loadRoles(pageParams) {
      try {
        const res = await getRoles(pageParams)
        this.roles = res.data.rows
        this.total = res.data.total
      } catch (err) {
        console.dir(err)
      }
    },
    handleSizeChange(val) {
      //   console.log(`每页 ${val} 条`)
      this.pageParams.pagesize = val
      this.pageParams.page = 1
      this.loadRoles(this.pageParams)
    },
    handleCurrentChange(val) {
      //   console.log(`当前页: ${val}`)
      this.pageParams.page = val
      this.loadRoles(this.pageParams)
    },
    // 删除功能
    deleteRole(id) {
      this.$confirm('此操作将永久删除,确认继续吗?', '提示', {
        cancelButtonText: '取消',
        confirmButtonText: '确认',
        type: 'warning'
      })
        .then(async() => {
          const res = await deleteRole(id)
          this.$message.success(res.message)
          if (this.roles.length === 1 && this.pageParams.page !== 1) {
            this.pageParams.page--
          }
          this.loadRoles(this.pageParams)
        })
        .catch(() => {})
    },
    indexFn(index) {
      return (
        index +
        1 +
        this.pageParams.page * this.pageParams.pagesize -
        this.pageParams.pagesize
      )
    },
    // 弹框确认按钮
    hSubmit() {
      this.$refs.roleForm.validate((valid) => {
        if (!valid) return
        this.flag ? this.hEait() : this.hAdd()
      })
    },
    // 添加操作
    async hAdd() {
      try {
        const res = await addRole(this.roleForm)
        this.$message.success(res.message)
        this.total++
        this.pageParams.page = Math.ceil(this.total / this.pageParams.pagesize)
        this.loadRoles(this.pageParams)
        this.showDialog = false
      } catch (error) {
        console.log(error)
      }
    },
    // 编辑操作
    async hEait() {
      try {
        const res = await updateRole(this.roleForm)
        this.$message.success(res.message)
        this.loadRoles(this.pageParams)
        this.showDialog = false
      } catch (error) {
        console.log(error)
      }
    },
    // 编辑弹窗
    doEait(data) {
      this.showDialog = true
      this.flag = true
      // 数据回显
      this.roleForm = { ...data }
    },
    // 添加弹窗
    doAdd() {
      this.showDialog = true
      this.flag = false
    }
  }
}
</script>
